﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace General.Tools
{
    #region AntiXss过滤工具

    /// <summary>
    /// AntiXss过滤工具
    /// </summary>
    public class XSSHelper
    {
        #region 字符串XSS验证

        /// <summary>
        /// 字符串XSS验证
        /// </summary>
        /// <param name="str"></param>
        /// <returns>返回true代表正常，返回false代表有XSS攻击</returns>
        public static bool XSSValidate(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return false;
            }

            return HttpUtility.HtmlDecode(Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(str)) == str;
        }

        #endregion

        #region 字符串XSS过滤

        /// <summary>
        /// 字符串XSS过滤
        /// </summary>
        /// <param name="str">待过滤字符串</param>
        /// <returns></returns>
        public static string XSSFilter(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return str;
            }

            return HttpUtility.HtmlDecode(Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(str));
        }

        /// <summary>
        /// 字符串XSS过滤
        /// </summary>
        /// <param name="dataList">待过滤集合</param>
        /// <returns></returns>
        public static List<string> XSSFilter(List<string> dataList)
        {
            List<string> ResultList = new List<string>();
            foreach (var item in dataList)
            {
                ResultList.Add(HttpUtility.HtmlDecode(Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(item)));
            }
            return ResultList;
        }

        /// <summary>
        /// 字符串XSS过滤
        /// </summary>
        /// <param name="dataList">待过滤数值</param>
        /// <returns></returns>
        public static string[] XSSFilter(string[] dataList)
        {
            string[] ResultList = new string[dataList.Length];
            int i = 0;
            foreach (var item in dataList)
            {
                ResultList[i] = (HttpUtility.HtmlDecode(Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(item)));
                i++;
            }
            return ResultList;
        }

        #endregion
    }

    #endregion
}
